<script setup>
import { ref, onMounted, toRefs, watch, nextTick } from "vue";
import { getDeviceData, addDeviceList } from "@/api/Dev2Connection";
import { message } from "@/utils/message";

onMounted(() => {
  getApiResourceList1();

  // 初始化 previousSelectedKeys 为当前选中的资源
  if (selectedItemKeys.value && selectedItemKeys.value.length > 0) {
    previousSelectedKeys.value = [...selectedItemKeys.value]; // 克隆选中的资源
  }
});

// 获取资源类型列表
const tableData = ref([]),
  deviceType = ref(undefined),
  deviceName = ref(null);

const getApiResourceList1 = () => {
  console.log("Device Type:", deviceType.value);
  console.log("Device Name:", deviceName.value);

  getDeviceData({
    deviceType: deviceType.value ? deviceType.value : "null",
    deviceName: deviceName.value ? deviceName.value : "null"
  })
    .then(res => {
      if (res.status === 200) {
        function shuffle(array) {
          for (let i = array.length - 1; i > 0; i--) {
            const j = Math.floor(Math.random() * (i + 1));
            [array[i], array[j]] = [array[j], array[i]];
          }
          return array;
        }
        res.data = shuffle(res.data); // 对返回的数据进行乱序
        tableData.value = res.data;

        // 搜索完成后，重新同步 selectedKeys 和 previousSelectedKeys
        nextTick(() => {
          if (selectedItemKeys.value && Array.isArray(selectedItemKeys.value)) {
            selectedItemKeys.value.forEach(item => {
              tableData.value.forEach(row => {
                if (item.id === row.id) {
                  multipleTableRef.value.toggleRowSelection(row, true);
                }
              });
            });
          }

          // 将当前选中项同步给 previousSelectedKeys
          previousSelectedKeys.value = [...selectedKeys.value];
        });
      } else {
        message(res.message, { type: "error" });
      }
    })
    .catch(err => {
      console.log(err);
    });
};
const getApiResourceList = () => {
  console.log("Device Type:", deviceType.value);
  console.log("Device Name:", deviceName.value);

  getDeviceData({
    deviceType: deviceType.value ? deviceType.value : "null",
    deviceName: deviceName.value ? deviceName.value : "null"
  })
    .then(res => {
      if (res.status === 200) {
        function shuffle(array) {
          for (let i = array.length - 1; i > 0; i--) {
            const j = Math.floor(Math.random() * (i + 1));
            [array[i], array[j]] = [array[j], array[i]];
          }
          return array;
        }
        res.data = shuffle(res.data); // 对返回的数据进行乱序
        tableData.value = res.data;

        // 搜索完成后，重新同步 selectedKeys 和 previousSelectedKeys
        nextTick(() => {
          if (selectedItemKeys.value && Array.isArray(selectedItemKeys.value)) {
            selectedItemKeys.value.forEach(item => {
              tableData.value.forEach(row => {
                if (item.id === row.id) {
                  multipleTableRef.value.toggleRowSelection(row, true);
                }
              });
            });
          }

          // 将当前选中项同步给 previousSelectedKeys
          previousSelectedKeys.value = [...selectedKeys.value];
        });
      } else {
        message(res.message, { type: "error" });
      }
    })
    .catch(err => {
      console.log(err);
    });
};
const props = defineProps({
  dialogVisible: {
    type: Boolean,
    default: false
  },
  selectedItemKeys: {
    type: Array,
    default() {
      return [];
    }
  }
});
const { dialogVisible, selectedItemKeys } = toRefs(props);
const emit = defineEmits(["childDialogVisible"]);

// watch(() => selectedItemKeys.value, (newValue) => {
//   console.log(newValue)
// })
// 弹框确认按钮
// 定义一个变量用于保存上一次的选中项
let previousSelectedKeys = ref([]);

// 弹框确认按钮
const confirmClick = () => {
  if (selectedKeys.value.length > 0) {
    // 比较 currentSelectedKeys 和 previousSelectedKeys
    const currentSelectedKeys = selectedKeys.value
      .map(key => key.id)
      .sort()
      .toString();
    const previousKeysString = previousSelectedKeys.value
      .map(key => key.id)
      .sort()
      .toString();

    if (currentSelectedKeys === previousKeysString) {
      // 如果选中项没有变化，给出提示，不进行提交操作
      message("资源未发生变化", { type: "warning" });
      return;
    }

    console.log("Selected keys:", selectedKeys.value);
    let arr = [];
    for (let i = 0; i < selectedKeys.value.length; i++) {
      arr.push({
        id: selectedKeys.value[i].id
      });
    }

    // 调用接口添加设备列表
    addDeviceList(arr)
      .then(res => {
        if (res.status === 200) {
          // 成功后保存当前选中项
          previousSelectedKeys.value = [...selectedKeys.value];

          // 关闭弹窗并提示用户
          message("添加成功", { type: "success" });
          emit("childDialogVisible", { type: "success", value: false });
          multipleTableRef.value.clearSelection();
          getApiTableDataList(); // 刷新数据
        } else {
          message(res.message, { type: "error" });
        }
      })
      .catch(err => {
        console.log(err);
      });
  } else {
    message("未选中任何资源", { type: "warning" });
  }
};

// 弹框取消按钮
const cancelClick = () => {
  multipleTableRef.value.clearSelection();
  emit("childDialogVisible", { type: "error", value: false });
};
// 关闭弹框回调
const handleClose = () => {
  multipleTableRef.value.clearSelection();
  emit("childDialogVisible", { type: "error", value: false });
};

// 弹窗打开回调
const handleOpen = () => {
  if (selectedItemKeys.value && selectedItemKeys.value.length > 0) {
    // 将选中的项目赋值给 selectedKeys 和 previousSelectedKeys
    selectedKeys.value = [...selectedItemKeys.value]; // 确保当前选中的项目
    previousSelectedKeys.value = [...selectedItemKeys.value]; // 初始化 previousSelectedKeys

    selectedItemKeys.value.forEach(item => {
      tableData.value.forEach(row => {
        if (item.id === row.id) {
          multipleTableRef.value.toggleRowSelection(row, true);
        }
      });
    });
  }
};

// 表格多选框
const selectedKeys = ref([]),
  multipleTableRef = ref();
const handleSelectionChange = keys => {
  selectedKeys.value = keys;
};
</script>

<template>
  <el-dialog
    :model-value="dialogVisible"
    title="添加"
    width="800"
    @open="handleOpen"
    @close="handleClose"
  >
    <div class="add-table">
      <div class="add-search">
        <el-form :inline="true">
          <el-form-item label="资源类型" style="width: 260px">
            <el-select
              v-model="deviceType"
              placeholder="请选择资源类型"
              clearable
              @change="getApiResourceList"
            >
              <el-option label="设备" value="设备" />
              <el-option label="产品" value="产品" />
              <el-option label="服务" value="服务" />
            </el-select>
          </el-form-item>
          <el-form-item label="资源名称" style="width: 260px">
            <el-input
              v-model="deviceName"
              placeholder="请输入资源名称"
              clearable
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="getApiResourceList"
              >搜索</el-button
            >
          </el-form-item>
        </el-form>
      </div>
      <div class="add-body">
        <el-table
          ref="multipleTableRef"
          class="custom-table"
          :data="tableData"
          border
          stripe
          max-height="390"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" align="center" />
          <el-table-column prop="deviceType" label="资源类型" align="center" />
          <el-table-column prop="deviceName" label="资源名称" align="center" />
        </el-table>
      </div>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="cancelClick">取消</el-button>
        <el-button type="primary" @click="confirmClick">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style lang="scss" scoped></style>
